package com.github.server.core;

import android.content.Context;

import com.github.livebase.util.base.Assert;
import com.github.livebase.util.base.IOUtil;
import com.github.server.interfaces.HttpRequest;
import com.github.server.interfaces.HttpResponse;
import com.github.server.interfaces.ResourceMapping;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName StaticResourceHandler
 * @description:
 * @author: biao532
 * @create: 2024-02-01 17:32
 * @Version 1.0
 **/
public class StaticResourceHandler extends SimpleHandler {
    private Context context;
    public StaticResourceHandler(Context context, String prefix) {
        super(prefix + "**");
        Assert.isTrue(prefix.endsWith("/"), "prefix must end with '/'");
        Assert.notNull(context, "context do not be null");
        this.context = context;
    }
    @Override
    public void handler(HttpRequest request, HttpResponse response) {
        String relaPath = request.getPath().substring(getPath().length() - 2);
        try(InputStream input = context.getAssets().open("static/" + relaPath)) {
            IOUtil.transferTo(input, response.getOutputStream());
        }catch (FileNotFoundException e) {
            response.setCode(404);
        }
        catch (IOException e) {
            response.setCode(500);
        }
    }
}
